<?php
/**
 * Parcl
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://parcl.com/license
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@parcl.com so we can send you a copy immediately.
 *
 * @category parcl
 * @package parcl-core
 * @copyright Copyright (c) 2006-2011 Mikael Knutsson (http://mikn.me)
 * @license http://parcl.com/license New BSD License
 */

namespace Parcl\Core {

	if(PARCL_EXEC !== 1) {
		die('<h1>Incorrect Access</h1>You cannot access this file directly.<br/>' .
			 'If you got this error message by clicking a link on the site,' .
			 'please notify the webmaster as soon as possible.');
	}

	/**
	 * @todo Port this to a parcel instead. Think it belongs there more.
	 */

	class DbSessions implements ISessionHandler {
		private $DB;
		private $savePath;
		private $name;

		public function __construct($sessionName, $cacheLimit, $savePath) {
			session_name($sessionName);
			session_cache_limiter($cacheLimit);
			session_save_path($savePath);
		}

		public function Open($savePath, $sessionName) {
			$registry = Registry::GetInstance();
			$this->DB = $registry->Get('DB');
			$this->savePath = $savePath;
			$this->name = $sessionName;
			return true;
		}
		public function Read($sessionID) {
			$registry = Registry::GetInstance();
			$session = ConstructQueries::ReadSession($registry, $this->savePath, $sessionID, $this->name);
			$sessionData = '';
			if(is_object($session)) {
				$sessionData = (string) $session->data;
			}
			return $sessionData;
		}
		public function Write($sessionID, $sessionData) {
			if(!empty($sessionData)) {
				$registry = Registry::GetInstance();
				ConstructQueries::WriteSession($registry, $this->savePath, $sessionID, $this->name, time(), $sessionData);
			}
			return true;
		}
		public function Close() {
			return true;
		}
		public function Destroy($sessionID) {
			$registry = Registry::GetInstance();
			ConstructQueries::DestroySession($registry, $this->savePath, $sessionID, $this->name);
			return true;
		}
		public function GarbageCollect($maxLifeTime) {
			$registry = Registry::GetInstance();
			ConstructQueries::GarbageCollectSessions($registry, $this->savePath, time() - $maxLifeTime);
			return true;
		}
	}
}